package com.hskn.hss.module.violationCfg.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.file.FileTypeUtils;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.common.ienum.ExcelTypeEnum;
import com.hskn.hss.module.common.to.ExcelReaderTO;
import com.hskn.hss.module.costdictitem.entity.CostDictItem;
import com.hskn.hss.module.costdictitem.service.ICostDictItemService;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.service.impl.TlCarTypeServiceImpl;
import com.hskn.hss.module.treemaintain.mapper.TreeMaintainMapper;
import com.hskn.hss.module.videoconfig.entity.VideoConfig;
import com.hskn.hss.module.violationCfg.entity.TlViolationCfg;
import com.hskn.hss.module.violationCfg.mapper.TlViolationCfgMapper;
import com.hskn.hss.module.violationCfg.service.ITlViolationCfgService;
import com.hskn.hss.module.violationCfg.to.ViolationCfgListTO;
import com.hskn.hss.module.violationCfg.vo.ViolationCfgExcelOutVO;
import com.hskn.hss.to.ForIdsTO;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-06
 */
@Slf4j
@RestController
@RequestMapping("/hss/tlviolationcfg")
@Api(tags = {"-tl_violation_cfg"}, description = "车辆违章费")
public class TlViolationCfgController {

    @Autowired
    private ITlViolationCfgService TlViolationCfgService;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private ICostDictItemService costDictItemService;
    @Autowired
    private ITlCarService carService;
    @Autowired
    private TlCarTypeServiceImpl carTypeService;

    /***
    /***
     * 新增信息
     * @param request
     * @return
     */
    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_violation_cfg", bean = TlViolationCfg.class, beanMapper = TlViolationCfgMapper.class, names = "carnumid")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public AjaxResult<Object> insert(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        return TlViolationCfgService.insert(params);
    }

    /**
     * 修改信息
     *
     * @param request
     * @return
     */
    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_violation_cfg", idKey = "id", bean = TlViolationCfg.class, beanMapper = TlViolationCfgMapper.class, names = "carnumid")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public AjaxResult<Object> update(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        return TlViolationCfgService.update(params);
    }

    /***
     * 删除角色信息
     * @param forIdsTO
     * @return
     */
    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_violation_cfg", idKey = "ids", bean = TlViolationCfg.class, beanMapper = TlViolationCfgMapper.class, names = "carnumid")
    @RequestMapping(value = "deleteByid", method = RequestMethod.POST)
    public AjaxResult<Object> deleteByid(@RequestBody @Validated ForIdsTO forIdsTO) {
        return TlViolationCfgService.deleteByid(forIdsTO);
    }

    /**
     * 根据Id获取信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getitemByid", method = RequestMethod.POST)
    public AjaxResult<Object> getitemByid(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        TlViolationCfg tlViolationCfg = null;
        try {
            tlViolationCfg = TlViolationCfgService.getitemByid(params.getString("id"));
            return AjaxResult.success(tlViolationCfg);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }
    }

    @RequestMapping(value = "getList", method = RequestMethod.POST)
    public AjaxResult<Object> getList(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject json = TlViolationCfgService.getList(entity, params);
            return AjaxResult.success(json);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }
    }

    /**
     * 车辆违章费导入接口
     *
     * @param request
     * @return
     */
//    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_violation_cfg", bean = TlViolationCfg.class, beanMapper = TlViolationCfgMapper.class, names = "carnumid")
    @ApiOperation(value = "车辆违章费导入接口", notes = "车辆违章费导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelReader")
    public AjaxResult excelReader(HttpServletRequest request, @ModelAttribute @Validated ExcelReaderTO excelReaderTo) {
        try {
            MultipartFile file = excelReaderTo.getFiles();
            if (Arrays.stream(ExcelTypeEnum.values()).noneMatch(s -> s.getName().equals(FileTypeUtils.getFileType(file.getOriginalFilename().toLowerCase())))) {
                return AjaxResult.fail("导入文件格式错误");
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            ExcelUtil<TlViolationCfg> util = new ExcelUtil<TlViolationCfg>(TlViolationCfg.class);
            List<TlViolationCfg> violationCfgList = util.importExcel(inputStream);
            if (violationCfgList.isEmpty()) {
                return AjaxResult.fail("导入内容为空");
            }
            TlViolationCfgService.excelReader(violationCfgList);
            if (TlViolationCfgService.saveBatch(violationCfgList)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.fail("导入失败");
            }
        } catch (ExcelReaderDataException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception exception) {
            exception.printStackTrace();
            return AjaxResult.fail();
        }

    }

    @ApiOperation(value = "车辆违章费导出接口", notes = "车辆违章费导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = ViolationCfgExcelOutVO.class)
    })
    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request, @RequestBody ViolationCfgListTO violationCfgListTo) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if((violationCfgListTo.getIds()!=null&&violationCfgListTo.getIds().isEmpty())){
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
            //查询数据
            List<TlViolationCfg> violationCfgList = TlViolationCfgService.getTlViolationCfgList(violationCfgListTo, format);
            //工具类实例化
            ExcelUtil<ViolationCfgExcelOutVO> util = new ExcelUtil<ViolationCfgExcelOutVO>(ViolationCfgExcelOutVO.class);
            //数据载体转换
            List<ViolationCfgExcelOutVO> violationCfgExcelOutVOList = JSONObject.parseArray(JSONObject.toJSONString(violationCfgList), ViolationCfgExcelOutVO.class);
            //构造结果集
            Map<String, SysDepart> departMap = departService.getDepartMap(new QueryWrapper<>());
            Map<String, CostDictItem> costDictItemMap = costDictItemService.getCostDictItemMap(new QueryWrapper<>());
            Map<String, TlCar> carMap = carService.getCarMap(new QueryWrapper<>());
            Map<String, TlCarType> carTypeMap = carTypeService.getCarTypeMap(new QueryWrapper<>());

            for (ViolationCfgExcelOutVO violationCfgExcelOutVO : violationCfgExcelOutVOList) {
                if (departMap.containsKey(violationCfgExcelOutVO.getDeptid())) {
                    violationCfgExcelOutVO.setDeptName(departMap.get(violationCfgExcelOutVO.getDeptid()).getDepartName());
                }
                if (costDictItemMap.containsKey(violationCfgExcelOutVO.getRepairreason())) {
                    violationCfgExcelOutVO.setRepairreasonName(costDictItemMap.get(violationCfgExcelOutVO.getRepairreason()).getCostname());
                }
                if (carMap.containsKey(violationCfgExcelOutVO.getCarnumid())) {
                    violationCfgExcelOutVO.setCarCardNum(carMap.get(violationCfgExcelOutVO.getCarnumid()).getCarnumber());
                }
                if (StringUtils.isNotEmpty(violationCfgExcelOutVO.getCosttime())) {
                    violationCfgExcelOutVO.setCosttimeString(format.format(violationCfgExcelOutVO.getCosttime()));
                }
                if(violationCfgExcelOutVO.getCartype() != null && carTypeMap != null && carTypeMap.containsKey(violationCfgExcelOutVO.getCartype())){
                    violationCfgExcelOutVO.setCartype(carTypeMap.get(violationCfgExcelOutVO.getCartype()).getTypename());
                }
            }
            //            导出
            return util.exportExcel(violationCfgExcelOutVOList, "车辆违章");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }

    @ApiOperation(value = "车辆违章费导出模板接口", notes = "车辆违章费模板导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = ViolationCfgExcelOutVO.class)
    })
    @PostMapping("excelExportTemplate")
    public com.hskn.hss.core.domain.AjaxResult excelExportTemplate(HttpServletRequest request) {
        try {
            //工具类实例化
            ExcelUtil<ViolationCfgExcelOutVO> util = new ExcelUtil<ViolationCfgExcelOutVO>(ViolationCfgExcelOutVO.class);
            //数据载体转换
            List<ViolationCfgExcelOutVO> violationCfgExcelOutVOList = new ArrayList<>();
            //导出
            return util.exportExcel(violationCfgExcelOutVOList, "车辆违章模板");
        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }
}

